<template>
  <view class="edit-vehicle-container">
    <view class="form-container">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        <view class="form-item">
          <view class="form-label required">车牌号</view>
          <input v-model="formData.vehiclePlate" placeholder="请输入车牌号" class="form-input" maxlength="10" />
        </view>
        <view class="form-item">
          <view class="form-label required">车辆类型</view>
          <picker mode="selector" :range="vehicleTypes" :range-key="'label'" :value="vehicleTypeIndex" @change="onVehicleTypeChange">
            <view class="picker-value">
              {{ vehicleTypeIndex >= 0 ? vehicleTypes[vehicleTypeIndex].label : '请选择车辆类型' }}
              <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
      </view>

      <!-- 驾驶员信息 -->
      <view class="form-section">
        <view class="section-title">驾驶员信息</view>
        <view class="form-item">
          <view class="form-label required">驾驶员姓名</view>
          <input v-model="formData.driverName" placeholder="请输入驾驶员姓名" class="form-input" maxlength="50" />
        </view>
        <view class="form-item">
          <view class="form-label required">联系电话</view>
          <input v-model="formData.driverPhone" type="number" placeholder="请输入联系电话" class="form-input" maxlength="11" />
        </view>
      </view>

      <!-- 证件信息 -->
      <view class="form-section">
        <view class="section-title">证件信息</view>
        <view class="form-item">
          <view class="form-label">行驶证照片</view>
          <view class="upload-area">
            <image-uploader
              upload-text="上传行驶证"
              upload-hint="请上传行驶证"
              :initial-image-url="formData.drivingLicensePhoto"
              @upload-complete="(url) => { formData.drivingLicensePhoto = url }"
            ></image-uploader>
          </view>
        </view>
        <view class="form-item">
          <view class="form-label">营运证照片</view>
          <view class="upload-area">
            <image-uploader
              upload-text="上传营运证"
              upload-hint="请上传道路运输证"
              :initial-image-url="formData.operatingLicensePhoto"
              @upload-complete="(url) => { formData.operatingLicensePhoto = url }"
            ></image-uploader>
          </view>
        </view>
      </view>

      <!-- 其他设置 -->
      <view class="form-section">
        <view class="section-title">其他设置</view>
        <view class="form-item">
          <view class="form-label">设为默认车辆</view>
          <switch :checked="formData.isDefault === '1'" @change="onDefaultChange" color="#1890ff" />
        </view>
        <view class="form-item">
          <view class="form-label">状态</view>
          <picker mode="selector" :range="statusOptions" :range-key="'label'" :value="statusIndex" @change="onStatusChange">
            <view class="picker-value">
              {{ statusIndex >= 0 ? statusOptions[statusIndex].label : '请选择状态' }}
              <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <view class="form-label">备注</view>
          <textarea v-model="formData.remark" placeholder="请输入备注信息" class="form-textarea" maxlength="200" />
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <button class="cancel-btn" @click="handleCancel">取消</button>
      <button class="submit-btn" @click="handleSubmit">保存</button>
    </view>
  </view>
</template>

<script>
import { getVehicle, updateVehicle } from '@/api/business/vehicle.js';
import ImageUploader from '@/components/image-uploader.vue';

export default {
  components: {
    ImageUploader
  },
  data() {
    return {
      vehicleId: null,
      formData: {
        vehiclePlate: '',
        vehicleType: '0',
        vehicleBrand: '',
        vehicleModel: '',
        vehicleColor: '',
        loadCapacity: '',
        vehicleVin: '',
        engineNumber: '',
        driverName: '',
        driverPhone: '',
        driverLicense: '',
        drivingLicensePhoto: '',
        operatingLicensePhoto: '',
        isDefault: '0',
        status: '0',
        remark: '',
      },
      vehicleTypes: [
        { value: '0', label: '货车' },
        { value: '1', label: '面包车' },
        { value: '2', label: '小型车' },
        { value: '3', label: '其他' },
      ],
      statusOptions: [
        { value: '0', label: '正常' },
        { value: '1', label: '停用' },
      ],
      vehicleTypeIndex: 0,
      statusIndex: 0,
    };
  },

  onLoad(options) {
    if (options.id) {
      this.vehicleId = options.id;
      this.loadVehicleInfo();
    }
  },

  methods: {
    // 加载车辆信息
    async loadVehicleInfo() {
      try {
        uni.showLoading({ title: '加载中...' });
        const res = await getVehicle(this.vehicleId);

        if (res.code === 200 && res.data) {
          const data = res.data;

          // 填充表单数据
          this.formData = {
            vehiclePlate: data.vehiclePlate || '',
            vehicleType: data.vehicleType || '0',
            vehicleBrand: data.vehicleBrand || '',
            vehicleModel: data.vehicleModel || '',
            vehicleColor: data.vehicleColor || '',
            loadCapacity: data.loadCapacity ? String(data.loadCapacity) : '',
            vehicleVin: data.vehicleVin || '',
            engineNumber: data.engineNumber || '',
            driverName: data.driverName || '',
            driverPhone: data.driverPhone || '',
            driverLicense: data.driverLicense || '',
            isDefault: data.isDefault || '0',
            status: data.status || '0',
            remark: data.remark || '',
            drivingLicenseImages: [],
            operatingLicenseImages: [],
          };

          // 处理图片
          if (data.drivingLicensePhoto) {
            // 只取第一张图片作为主图显示
            const images = data.drivingLicensePhoto.split(',').filter((img) => img);
            this.formData.drivingLicensePhoto = images[0] || '';
          }
          if (data.operatingLicensePhoto) {
            // 只取第一张图片作为主图显示
            const images = data.operatingLicensePhoto.split(',').filter((img) => img);
            this.formData.operatingLicensePhoto = images[0] || '';
          }

          // 设置选择器索引
          this.vehicleTypeIndex = this.vehicleTypes.findIndex((item) => item.value === this.formData.vehicleType);
          this.statusIndex = this.statusOptions.findIndex((item) => item.value === this.formData.status);
        }
      } catch (error) {
        console.error('加载车辆信息失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none',
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 选择车辆类型
    onVehicleTypeChange(e) {
      this.vehicleTypeIndex = e.detail.value;
      this.formData.vehicleType = this.vehicleTypes[this.vehicleTypeIndex].value;
    },

    // 选择状态
    onStatusChange(e) {
      this.statusIndex = e.detail.value;
      this.formData.status = this.statusOptions[this.statusIndex].value;
    },

    // 默认车辆开关
    onDefaultChange(e) {
      this.formData.isDefault = e.detail.value ? '1' : '0';
    },



    // 验证表单
    validateForm() {
      if (!this.formData.vehiclePlate) {
        uni.showToast({
          title: '请输入车牌号',
          icon: 'none',
        });
        return false;
      }

      // 验证车牌号格式
      const plateReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
      if (!plateReg.test(this.formData.vehiclePlate)) {
        uni.showToast({
          title: '车牌号格式不正确',
          icon: 'none',
        });
        return false;
      }

      if (!this.formData.driverName) {
        uni.showToast({
          title: '请输入驾驶员姓名',
          icon: 'none',
        });
        return false;
      }

      if (!this.formData.driverPhone) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none',
        });
        return false;
      }

      // 验证手机号格式
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.formData.driverPhone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none',
        });
        return false;
      }

      return true;
    },

    // 提交表单
    async handleSubmit() {
      if (!this.validateForm()) {
        return;
      }

      try {
        uni.showLoading({ title: '保存中...' });

        // 准备提交数据
        const submitData = {
          vehicleId: this.vehicleId,
          ...this.formData
        };

        // 转换载重量为数字
        if (submitData.loadCapacity) {
          submitData.loadCapacity = parseFloat(submitData.loadCapacity);
        }

        const res = await updateVehicle(submitData);

        if (res.code === 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success',
          });

          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || '修改失败',
            icon: 'none',
          });
        }
      } catch (error) {
        console.error('修改车辆失败:', error);
        uni.showToast({
          title: '修改失败',
          icon: 'none',
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 取消
    handleCancel() {
      uni.navigateBack();
    },
  },
};
</script>

<style scoped>
.edit-vehicle-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.form-container {
  padding: 20rpx;
}

.form-section {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-left: 12rpx;
  border-left: 4rpx solid #1890ff;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  width: 180rpx;
  font-size: 28rpx;
  color: #666;
}

.form-label.required::before {
  content: '*';
  color: #ff4d4f;
  margin-right: 8rpx;
}

.form-input {
  flex: 1;
  height: 70rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
}

.form-textarea {
  flex: 1;
  min-height: 150rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  padding: 20rpx 24rpx;
  font-size: 28rpx;
}

.picker-value {
  flex: 1;
  height: 70rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  padding: 0 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  color: #333;
}

/* 上传区域 */
.upload-area {
  flex: 1;
}

.upload-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.upload-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
}

.upload-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 36rpx;
  height: 36rpx;
  background: #ff4d4f;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed #d9d9d9;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.upload-tips {
  font-size: 24rpx;
  color: #999;
  margin-top: 16rpx;
}

/* 底部按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  gap: 30rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.cancel-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  background: #fff;
  color: #666;
  border: 2rpx solid #d9d9d9;
  font-size: 32rpx;
}

.submit-btn {
  flex: 2;
  height: 88rpx;
  border-radius: 44rpx;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: #fff;
  border: none;
  font-size: 32rpx;
}
</style>
